import constant from '../utils/constant'
import api from '../api/index'

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '')
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// 首字母大小
export function titleCase(str) {
  return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
}

// 下划转驼峰
export function camelCase(str) {
  return str.replace(/_[a-z]/g, str1 => str1.substr(-1).toUpperCase())
}

// 转换字符串，undefined,null等转化为''
export function parseStrEmpty(str) {
  if (!str || str === 'undefined' || str === 'null') {
    return ''
  }
  return str
}

export function isNumberStr(str) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
}

// 是否为空
export function isNull(obj) {
  if (obj === null || typeof (obj) === 'undefined' || obj === undefined || obj === '') {
    return true
  } else if (obj instanceof Array && obj.length === 0) {
    return true
  } else if (JSON.stringify(obj) === '{}') {
    return true
  } else {
    return false
  }
}

// 验证是否为blob格式
export async function blobValidate(data) {
  try {
    const text = await data.text()
    JSON.parse(text)
    return false
  } catch (error) {
    return true
  }
}

// 字符串格式化(%s )
export function sprintf(str) {
  const args = arguments
  let flag = true
  let i = 1
  str = str.replace(/%s/g, function() {
    const arg = args[i++]
    if (typeof arg === 'undefined') {
      flag = false
      return ''
    }
    return arg
  })
  return flag ? str : ''
}

export function replaceAll(str, find, replace) {
  return str.replace(new RegExp(find, 'g'), replace);
}

/**
* 参数处理
* @param {*} params  参数
*/
export function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    var part = encodeURIComponent(propName) + '='
    if (value !== null && typeof (value) !== 'undefined') {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && typeof (value[key]) !== 'undefined') {
            const params = propName + '[' + key + ']'
            var subPart = encodeURIComponent(params) + '='
            result += subPart + encodeURIComponent(value[key]) + '&'
          }
        }
      } else {
        result += part + encodeURIComponent(value) + '&'
      }
    }
  }
  return result
}


export function switchTabBar(that, name){
  let currentTarbar  = that.getTabBar();
  currentTarbar.setData({
    // active: 0,
    // selected: 0
    pageCur: name
  })
}


export function getStar(birthday){
	let arr = birthday.split('-')
	let month= parseInt(arr[1])
    let day=parseInt(arr[2])
    switch(month){
        case 1:
            if(day>19){return "水瓶座"}
            else return "摩羯座";
        case 2:
            if(day>18){return "双鱼座"}
            else return "水瓶座"
        case 3:
            if(day>20){return "白羊座"}
            else return "双鱼座"
        case 4:
            if(day>19){return "金牛座"}
            else return "白羊座"
        case 5:
            if(day>20){return "双子座"}
            else return "金牛座"
        case 6:
            if(day>21){return "巨蟹座"}
            else return "双子座"
        case 7:
            if(day>22){return "狮子座"}
            else return "巨蟹座"
        case 8:
            if(day>22){return "处女座"}
            else return "狮子座"
        case 9:
            if(day>22){return "天秤座"}
            else return"处女座"
        case 10:
            if(day>23){return "天蝎座"}
            else return "天秤座"
        case 11:
            if(day>20){return "射手座"}
            else return "天蝎座"
        case 12:
            if(day>21){return "摩羯座"}
            else return"射手座"
		}
		
}

export function getClassColor(className, defaultColor){
	const colors = constant.COLOR_LIST
	if(className){
		let color = null
		for(const i in colors){
			if(colors[i].class == className){
				color =  colors[i].name
				break
			}
		}
		if(color){
			return color
		}else{
			return defaultClassName
		}
	}else{
		return defaultClassName
	}
}

export async function getArea(areaRange, province, city, area) {
  let txt = ''
  function areaName(areaRange, province, city, area) {
    if(!isNull(province)){
      for(const i in areaRange[0]){
        if(areaRange[0][i].id == province){
          txt = areaRange[0][i].fullname
          break
        }
      }
    }
    if(!isNull(city)){
      for(const i in areaRange[1]){
        if(areaRange[1][i].id == city){
          txt = txt + areaRange[1][i].fullname
          break
        }
      }
    }
    if(!isNull(area)){
      for(const i in areaRange[2]){
        if(areaRange[2][i].id == area){
          txt = txt + areaRange[2][i].fullname
          break
        }
      }
    }
  }
  if(areaRange == '' || areaRange == null){
    await api.common.getAreas().then(res=>{
      areaName(res,province, city, area)
      return txt
    })
  }else{
    areaName(areaRange,province, city, area)
    return txt
  }
  
}

export async function getDict(dictType, dictVal) {
  let dict = await api.common.getDictData(dictType).then(res=>{
    for(const i in res){
      if(res[i].dictValue == dictVal){
        console.log(1)
        return res[i]
      }
    }
  })
  return dict
}
